package core.web.spring;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import apps.project.upload.UploadFileBean;

@Controller
@RequestMapping("/jsp")
public class SpringMVCUtils {
	
	@RequestMapping("/view")
	public String getWebinfjsp(@RequestParam("p")String path) {
		return path;
	}
	
	/**
	 * 对返回的数组进行加工，可以定义返回哪些字段及字段的重命名
	 * @param list
	 * @param mapper
	 * @return
	 */
	public static List<Map<String, Object>> getMapperJSON(List list,Map<String, String> mapper)  {
		List<Map<String, Object>> returnList=new ArrayList<Map<String,Object>>();
		for(Object object:list) {
			Iterator<Entry<String, String>> entryKeyIterator = mapper.entrySet().iterator(); 
			Map<String, Object> itemMap=new HashMap<String, Object>();
			while (entryKeyIterator.hasNext()) {   
			    Entry<String, String> e = entryKeyIterator.next();   
			    String key=e.getKey();
			    String value=e.getValue();
			    Object mapperValue;
				try {
					mapperValue = PropertyUtils.getProperty(object, key);
				    itemMap.put(value, mapperValue);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return null;
				} 
			} 
			returnList.add(itemMap);
		}
		return returnList;
	}
	
	public static Map getPager(Page pageResult,Map<String, String> mapper,boolean flag) {
        Map attributes = new HashMap();
        attributes.put("total", pageResult.getTotalElements());
        List<UploadFileBean> list=pageResult.getContent();
        if(flag) {
    		List<Map<String, Object>> returnList=SpringMVCUtils.getMapperJSON(list, mapper);
            attributes.put("rows", returnList);	        	
        }else {
            attributes.put("rows", list);	        	
        }
	
		return attributes;
	}
	
	
}
